/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.mam.rbac.web;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.data.domain.Page;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.foreveross.bsl.common.utils.enums.AccountStatus;
import com.foreveross.bsl.common.utils.exception.AppExcType;
import com.foreveross.bsl.common.utils.exception.ApplicationException;
import com.foreveross.bsl.common.utils.web.QueryFilter;
import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.common.utils.web.model.PageMustache;
import com.foreveross.bsl.common.utils.web.model.QueryModelHelper;
import com.foreveross.bsl.common.utils.web.model.SelectBoxModel;
import com.foreveross.bsl.common.utils.web.model.SortInfoModel;
import com.foreveross.bsl.mam.rbac.application.AdminApplication;
import com.foreveross.bsl.mam.rbac.application.vo.AdminVO;


/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-11-8
 *
 */
@Controller
@RequestMapping("/mam-rbac/admins")
public class AdminController  extends  RbacBaseController {
 
	@Inject
	private AdminApplication adminApplication;

	@ResponseBody
	@RequestMapping("/add")
	public Map<String, Object> add(AdminVO admin)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		
		// check the username 
		AdminVO u = adminApplication.getEntityByUserName(admin.getUsername());
		if (u != null)
		{
			throw new ApplicationException(AppExcType.BUS_TYPE, AppExcType.WEB_LAYER, AppExcType.MAM_MODUL, "032", "username registered");
		}
		admin = adminApplication.saveEntity(admin);
		result.put("result", "success");
		return result;
	}

	@ResponseBody
	@RequestMapping("/delete")
	public Map<String, Object> delete(String[] ids)	{
		Map<String, Object> result = new HashMap<String, Object>();
		if (ids != null) {
			for (String id : ids) {
				adminApplication.deleteEntity(id);
			}
		}
		result.put("result", "success");
		return result;
	}

	@ResponseBody
	@RequestMapping("/get")
	public Map<String, Object> get(@RequestParam String id)	{
		Map<String, Object> result = new HashMap<String, Object>();
		AdminVO admin = adminApplication.getEntity(id);
		result.put("data", admin);
		return result;
	}

	/**
	 * admin list
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model, @RequestParam(value = "page", defaultValue = "1") int pageNumber, @RequestParam(value = "page.size", defaultValue = "10") int pageSize, HttpServletRequest request)
	{

		String queryUrl = "/mam-rbac/admins/list";
		QueryModelHelper queryHelper = new QueryModelHelper(queryUrl, makeQueryFields(), makeSortInfo());
		QuerySpecs querySpecs = queryHelper.populateQueryModel(model, request);
		Page<AdminVO> admins = adminApplication.findByPageable(pageNumber - 1, pageSize, querySpecs);
		if(admins != null){
			for (AdminVO adminVO : admins) {
				AccountStatus s = AccountStatus.getByCode(adminVO.getStatus());
				adminVO.setStatusView(AccountStatus.getName(s));
				String name = null;
				switch (s) {
				case Auditing:
					name = "审核";
					break;
				case Inactive:
					name = "激活";
					break;
				case Disabled:
					name = "启用";
					break;
				case Suspended:
					name = "启用";
					break;
				case Normal:
					name = "暂停";
					break;
				default:
					name = "启用";
					break;
				}
				adminVO.setOpView(name);
			}
		}
		QueryFilter firstFilter = querySpecs.getFirstFilter();
		if (firstFilter.getFieldName() != null)
		{
			model.addAttribute("fieldName", "q_" + firstFilter.getOperator().name() + "_" + firstFilter.getFieldName());
		}
		model.addAttribute("page", new PageMustache(admins, 10));
		model.addAttribute("list", admins.getContent());

		return "rbac/admin-list";
	}

	private final SortInfoModel makeSortInfo()	{
		SortInfoModel sim = new SortInfoModel();

		sim.setSortEntry("username", "用户名", true);
		sim.setSortEntry("name", "昵称", true);
		return sim;
	}
	
	private final SelectBoxModel makeQueryFields()	{
		SelectBoxModel sbm = new SelectBoxModel();
		sbm.addOption("LIKE_username", "用户名");
		sbm.addOption("LIKE_name", "姓名");
		return sbm;
	}

	/**
	 * change user status
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/change_status")
	public Map<String, Object> changeStatus(String id, String status)
	{
		Map<String, Object> result = new HashMap<String, Object>();

		AdminVO admin = adminApplication.getEntity(id);
		AccountStatus as = AccountStatus.getByCode(status);
		if (as == null)	{
			throw new ApplicationException(AppExcType.BUS_TYPE, AppExcType.WEB_LAYER, AppExcType.MAM_MODUL, "003", "the status code is not exist.");
		}
		admin.setStatus(as.getValue());
		adminApplication.updateEntity(id, admin);
		result.put("result", "success");
		return result;
	}

	/**
	 * reset password
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/reset_password")
	public Map<String, Object> resetPassword(String id)	{
		Map<String, Object> result = new HashMap<String, Object>();
		AdminVO admin = adminApplication.getEntity(id);
		if (admin != null)
		{
			admin.setPassword("000000");
			Md5PasswordEncoder md = new Md5PasswordEncoder();
			String encodePassword = md.encodePassword(admin.getPassword(), admin.getUsername());
			admin.setPassword(encodePassword);
			adminApplication.updateEntity(id, admin);
		}
		result.put("result", "success");
		return result;
	}

	/**
	 * set password
	 * 
	 * @param id
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/set_password")
	public Map<String, Object> setPassword(String id, String password)
	{
		Map<String, Object> result = new HashMap<String, Object>();
		AdminVO admin = adminApplication.getEntity(id);
		if (admin != null)
		{
			Md5PasswordEncoder md = new Md5PasswordEncoder();
			String encodePassword = md.encodePassword(password, admin.getUsername());
			admin.setPassword(encodePassword);
			adminApplication.updateEntity(id, admin);
		}
		result.put("result", "success");
		return result;
	}

	/**
	 * update admin
	 * 
	 * @param 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/update")
	public Map<String, Object> update(AdminVO admin)	{
		Map<String, Object> result = new HashMap<String, Object>();
		AdminVO a = adminApplication.getEntity(admin.getId());
		a.setName(admin.getName());
		a.setSex(admin.getSex());
		a.setTelephone(admin.getTelephone());
		a.setAddress(admin.getAddress());
		adminApplication.updateEntity(admin.getId(), a);
		result.put("result", "success");
		return result;
	}

}
